/**
 * zbestpayment.com Inc.
 * Copyright (c) 2004-2017 All Rights Reserved.
 */
package com.zbest.zpay.gw.processor;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zbest.zpay.gw.assemble.MessageAssembleManager;
import com.zbest.zpay.gw.dal.dao.GwTransactionContentDAO;
import com.zbest.zpay.gw.dal.mapper.GwTransactionUniqueMapper;
import com.zbest.zpay.gw.dal.model.GwTransactionUniqueDO;
import com.zbest.zpay.gw.dispatch.MessageDispatcherManager;
import com.zbest.zpay.gw.model.MessageContext;
import com.zbest.zpay.gw.parser.MessageParserManager;
import com.zbest.zpay.service.gw.model.GwKeyEnum;

/**
 * 
 *
 * @author Administrator
 * @version $Id: MessageSenderImpl.java, v 0.1 2017-4-12 下午11:03:03
 *          Administrator Exp $
 */
@Service("messageSender")
public class MessageSenderImpl implements MessageProcessor {

    @Resource
    private MessageAssembleManager    messageAssembleManager;

    @Resource
    private MessageParserManager      messageParserManager;

    @Resource
    private MessageDispatcherManager  messageDispatcherManager;

    @Resource
    private GwTransactionUniqueMapper gwTransactionUniqueMapper;

    @Resource
    private GwTransactionContentDAO   gwTransactionContentDAO;

    /**
     * @see com.zbest.zpay.gw.processor.MessageProcessor#process(java.lang.String,
     *      java.lang.String, java.util.Map)
     */
    @Override
    public MessageContext process(String channelId, Map<String, Object> data) {

        // 1.写幂等表，做幂等控制
        GwTransactionUniqueDO gwTransactionUniqueDO = new GwTransactionUniqueDO();
        gwTransactionUniqueDO
            .setUniqueKey(channelId + data.get(GwKeyEnum.INST_SERIAL_NO.getCode()));
        gwTransactionUniqueMapper.insert(gwTransactionUniqueDO);

        // 2.组装报文
        MessageContext context = new MessageContext();
        context.setChannelId(channelId);
        context.setRequestData(data);
        messageAssembleManager.assemble(context);

        // 3.保存报文，组装完报文就保存了
        //saveSendMessage(context);

        // 4.发送报文
        messageDispatcherManager.send(context);

        // 5.解析返回结果
        messageParserManager.parse(context);

        // 6.保存返回内容
        gwTransactionContentDAO.update(null, null);

        return context;
    }

    /**
     * 保存报文
     * 
     * @param context
     */
    /*private void saveSendMessage(MessageContext context) {
    	GwTransactionContentDO gwTransactionContentDO = new GwTransactionContentDO();
    	gwTransactionContentDO.setChannelId(context.getChannelId());
    	String instSerialNo = context.getRequestData(GwKeyEnum.INST_SERIAL_NO.getCode());
    	gwTransactionContentDO.setInstSerialNo(instSerialNo);
    	gwTransactionContentDO.setRequestContent(context.getSendMessage().toString());
    	gwTransactionContentMapper.insert(gwTransactionContentDO);
    }*/

}
